<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import {
  getPatientList,
  addPatient,
  editPatient,
  delPatient
} from '@/services/user'
import { PatientList, Patient } from '@/types/user.d.ts'
import { nameRules, idCardRules } from '@/utils/rules'
import type { FormInstance } from 'vant'
import { showConfirmDialog, showSuccessToast } from 'vant' // 提示函数组件需要单独引入
import { useRoute } from 'vue-router'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'

const patientList = ref<PatientList>([]) //患者列表

const options = [
  //性别单选选项
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
const gender = ref(1) //性别
const show = ref(false) //popup弹层
const initPatient: Patient = {
  //患者信息对象
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}
const patient = ref<Patient>({ ...initPatient }) //患者信息
const form = ref<FormInstance>() //患者表单
// 是否是选择患者
const route = useRoute()
const isChange = computed(() => route.query.isChange === '1')
const patientId = ref<string>() //选择的节点
const selectedPatient = (item: Patient) => {
  // 记录选择的节点
  // 只有在选择患者时才能选中高亮
  if (isChange.value) {
    patientId.value = item.id
  }
}
const store = useConsultStore() // 极速问诊仓库
const router = useRouter() //路由实例

// 获取患者列表
const getpatientList = async () => {
  const res = await getPatientList()
  console.log(res, 'res')
  patientList.value = res.data
  // 设置默认选中的ID，当你是选择患者的时候，且有患者信息的时候
  if (isChange.value && patientList.value.length) {
    const defPatient = patientList.value.find((item) => item.defaultFlag === 1) //获取默认患者
    // 若是有默认患者就高亮否则是高亮第一个
    if (defPatient) patientId.value = defPatient.id
    else patientId.value = patientList.value[0].id
  }
}
// 添加或修改患者弹层
const showPopup = (item?: Patient) => {
  // 通过是否传递患者信息区分呢新增或修改
  if (item) {
    // 编辑：解构出需要的数据并赋值回显信息
    const { id, gender, name, idCard, defaultFlag } = item
    patient.value = { id, gender, name, idCard, defaultFlag }
  } else {
    // 新增：
    patient.value = { ...initPatient } //打开侧边栏重置表单
  }
  show.value = true
}
// 添加或修改患者表单校验并完成操作
const onSubmit = async () => {
  await form.value?.validate()
  // 身份证倒数第二位，单数是男，双数是女
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗？'
    })
  }
  // 校验通过,新增或编辑患者
  // console.log('通过校验')
  patient.value.id
    ? await editPatient(patient.value)
    : await addPatient(patient.value)
  show.value = false
  getpatientList()
  showSuccessToast(patient.value.id ? '修改成功' : '添加成功')
}
// 删除患者
const remove = async () => {
  await showConfirmDialog({
    title: '温馨提示',
    message: `您确认要删除 ${patient.value.name} 患者信息吗 ？`
  })
  await delPatient(patient.value.id)
  show.value = false
  getpatientList()
  showSuccessToast('删除成功')
}

// 默认值需要转换，通过计算属性转换。
const defaultFlag = computed({
  get() {
    return patient.value.defaultFlag === 1 ? true : false
  },
  set(value) {
    patient.value.defaultFlag = value ? 1 : 0
  }
})

// 下一步
const next = async () => {
  //校验是否选择患者，没有直接返回
  if (!patientId.value) return showToast('请选就诊择患者')
  store.setPatient(patientId.value) //记录患者
  router.push('/consult/pay') //跳转到支付页
}

onMounted(() => {
  getpatientList()
})
</script>

// 家庭档案
<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        v-for="item in patientList"
        :key="item.id"
        @click="selectedPatient(item)"
        :class="{ selected: patientId === item.id }"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <!-- 身份证脱敏处理："^(.{6})",匹配第一个$1;".+",匹配中间字符;"(.{4})$",匹配第二个$2 -->
          <span class="id">{{
            item.idCard.replace(/^(.{6}).+(.{4})$/, '\$1********\$2')
          }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}</span>
        </div>
        <div class="icon" @click="showPopup(item)">
          <cp-icon name="user-edit" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <!-- <div class="patient-item">
        <div class="info">
          <span class="name">李富贵</span>
          <span class="id">321333********6164</span>
          <span>男</span>
          <span>32岁</span>
        </div>
        <div class="icon"><cp-icon name="user-edit" /></div>
      </div> -->
      <div
        class="patient-add"
        v-if="patientList.length < 6"
        @click="showPopup()"
      >
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>

    <!-- 添加患者弹层 -->
    <van-popup v-model:show="show" position="right">
      <cp-nav-bar
        :back="() => (show = false)"
        :title="patient.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        @click-right="onSubmit"
      ></cp-nav-bar>
      <!-- 患者表单 -->
      <van-form autocomplete="off" ref="form">
        <van-field
          :rules="nameRules"
          v-model="patient.name"
          label="真实姓名"
          placeholder="请输入真实姓名"
        />
        <van-field
          :rules="idCardRules"
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn v-model="patient.gender" :options="options">
            </cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>
      <!-- 删除患者按钮 -->
      <van-action-bar v-if="patient.id">
        <van-action-bar-button @click="remove">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" @click="next" round block>下一步</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;

  // popup弹层
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }

  // 底部操作栏
  .van-action-bar {
    padding: 0 10px;
    margin-bottom: 10px;

    .van-button {
      color: var(--cp-price);
      background-color: var(--cp-bg);
    }
  }
}

.patient-list {
  padding: 15px;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;

  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;

    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;

      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }

      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }

  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }

  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);

    .icon {
      color: var(--cp-primary);
    }
  }
}

.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;

  .cp-icon {
    font-size: 24px;
  }
}

.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}

.pb4 {
  padding-bottom: 4px;
}

.patient-change {
  padding: 15px;

  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }

  > p {
    color: var(--cp-text3);
  }
}

.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
</style>
